package com.qmuiteam.qmui.popup

import android.annotation.SuppressLint
import android.widget.PopupWindow
import com.qmuiteam.qmui.util.QMUIReflectHelper
import com.qmuiteam.qmui.widget.popup.QMUIPopup

@SuppressLint("ClickableViewAccessibility")
fun <T : QMUIPopup> T.dismissIfOutsideTouchV2(dismissIfOutsideTouch: Boolean): T {
    val mWindow: PopupWindow? = QMUIReflectHelper.getFieldValue(this, "mWindow")
    mWindow?.isOutsideTouchable = dismissIfOutsideTouch
    mWindow?.setTouchInterceptor { v, event ->
        val location = IntArray(2)
        val contentView = this.contentView
        if (contentView != null) {
            contentView.getLocationOnScreen(location)
            val width = contentView.width
            val height = contentView.height
            val x = event.rawX
            val y = event.rawY
            // 判断触摸点是否在 PopupWindow 视图的区域外
            val isOutside = x < location[0] || x > location[0] + width || y < location[1] || y > location[1] + height
            if (!dismissIfOutsideTouch && isOutside) {
                return@setTouchInterceptor true
            }
        }
        return@setTouchInterceptor false
    }
    return this
}